import json
import socket
import threading
from server.auth import authenticate
from server.methods import METHODS
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('rpc_server')

class RPCServer:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.server_socket = None
        self.threads = []

    def start(self):
        """启动服务器"""
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.bind((self.host, self.port))
        self.server_socket.listen(5)
        logger.info(f"Server started on {self.host}:{self.port}")

        try:
            while True:
                client_socket, client_address = self.server_socket.accept()
                logger.info(f"Accepted connection from {client_address}")
                client_thread = threading.Thread(target=self.handle_client, args=(client_socket,))
                client_thread.daemon = True
                client_thread.start()
                self.threads.append(client_thread)
        except KeyboardInterrupt:
            logger.info("Server shutting down...")
        finally:
            self.server_socket.close()

    def handle_client(self, client_socket):
        """处理客户端请求"""
        try:
            request_data = client_socket.recv(4096).decode('utf-8')
            if not request_data:
                return

            try:
                request = json.loads(request_data)
            except json.JSONDecodeError:
                response = self._error_response(-32700, "Parse error", id=None)
                client_socket.sendall(json.dumps(response).encode('utf-8'))
                return

            # 检查请求格式
            if not all(key in request for key in ('auth', 'method', 'params')):
                response = self._error_response(-32600, "Invalid Request", id=request.get('id'))
                client_socket.sendall(json.dumps(response).encode('utf-8'))
                return

            # 认证
            auth = request.get('auth', {})
            username = auth.get('username')
            password = auth.get('password')
            if not authenticate(username, password):
                response = self._error_response(-32500, "Authentication failed", id=request.get('id'))
                client_socket.sendall(json.dumps(response).encode('utf-8'))
                return

            # 执行方法
            method_name = request.get('method')
            params = request.get('params', [])
            method = METHODS.get(method_name)

            if method is None:
                response = self._error_response(-32601, "Method not found", id=request.get('id'))
            else:
                try:
                    result = method(*params)
                    response = {
                        'result': result,
                        'error': None,
                        'id': request.get('id')
                    }
                except Exception as e:
                    response = self._error_response(-32500, str(e), id=request.get('id'))

            client_socket.sendall(json.dumps(response).encode('utf-8'))
        except Exception as e:
            logger.error(f"Error handling client: {e}")
        finally:
            client_socket.close()

    def _error_response(self, code, message, id):
        """生成错误响应"""
        return {
            'result': None,
            'error': {
                'code': code,
                'message': message
            },
            'id': id
        }

if __name__ == "__main__":
    import configparser
    config = configparser.ConfigParser()
    config.read('../config/config.ini')
    
    host = config.get('server', 'host', fallback='localhost')
    port = config.getint('server', 'port', fallback=8000)
    
    server = RPCServer(host, port)
    server.start()    
